package com.example.service;

import com.example.domain.User;
import com.example.repository.UserRepository;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    
    public User getUser(User user) {
        final Optional<User> optionalUser = userRepository.findByAccountAndPassword(user.getAccount(), user.getPassword());
        return optionalUser.orElseGet(User::new);
    }
    
    public List<User> list(final int type, final int page, final int rows, final String sortColumn, final String order) {
        Sort sort = new Sort(Sort.Direction.fromString(order), sortColumn);
        final PageRequest pageRequest = PageRequest.of(page, rows, sort);
        final Page<User> all = userRepository.findAllByType(type, pageRequest);
        final List<User> content = all.getContent();
        return content;
    }
    
    public List<User> getAllUser(){
        final Iterable<User> all = userRepository.findAll();
        return Lists.newArrayList(all);
    }
}
